//com.tanhua.server.service.IMService
package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.api.HuanXinApi;
import com.tanhua.dubbo.api.QuanZiApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UsersApi;
import com.tanhua.dubbo.pojo.*;
import com.tanhua.dubbo.pojo.HuanXinUser;
import com.tanhua.dubbo.pojo.UserInfo;
import com.tanhua.dubbo.pojo.Users;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.server.pojo.Announcement;
import com.tanhua.server.vo.*;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.UserInfoVo;
import com.tanhua.server.vo.UsersVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class IMService {

    @DubboReference(version = "1.0.0")
    private HuanXinApi huanXinApi;

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;


    @DubboReference(version = "1.0.0")
    private UsersApi usersApi;

    @DubboReference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private AnnouncementService announcementService;

    public UserInfoVo queryUserInfoByUserName(String userName) {
        HuanXinUser huanXinUser = this.huanXinApi.queryHuanXinUserByUserName(userName);
        if (null == huanXinUser) {
            return null;
        }
        UserInfo userInfo = this.userInfoApi.queryByUserId(huanXinUser.getUserId());
        UserInfoVo userInfoVo = BeanUtil.toBeanIgnoreError(userInfo, UserInfoVo.class);

        userInfoVo.setGender(userInfo.getSex().toString().toLowerCase());
        userInfoVo.setMarriage(StrUtil.equals("已婚", userInfo.getMarriage()) ? 1 : 0);
        return userInfoVo;
    }

    /**
     * 添加好友
     *
     * @param friendId 好友id
     */
    public boolean addContacts(Long friendId) {
        Long userId = UserThreadLocal.get();

        //添加好友关系到环信
        Boolean result = this.huanXinApi.addUserFriend(userId, friendId);

        //添加好友关系到MongoDB
        if (result) {
            return this.usersApi.saveUsers(userId, friendId) != null;
        }
        return false;
    }

    /**
     * 查询联系人列表
     *
     * @param page
     * @param pageSize
     * @param keyword  根据关键字搜索
     * @return
     */
    public PageResult queryContactsList(Integer page, Integer pageSize, String keyword) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        Long userId = UserThreadLocal.get();
        List<UserInfo> userInfoList ;
        List<UsersVo> result  = new ArrayList<>();;
        if (StrUtil.isEmpty(keyword)) {
            //按顺序查询，按照添加时间倒序排序
            PageInfo<Users> pageInfo = this.usersApi.queryUsersList(userId, page, pageSize);
            if (CollUtil.isEmpty(pageInfo.getRecords())) {
                return pageResult;
            }
            //获取用户信息列表
            //TODO 按照Records列表中的顺序进行输出(完成)
            List<Users> records = pageInfo.getRecords();

            Map<Long, UserInfo> friendIdMap = this.userInfoApi.queryMapByUserIdList(CollUtil.getFieldValues(pageInfo.getRecords(), "friendId"));
            //按照Records列表中的顺序进行输出
            for (Users record : records) {
                UserInfo userInfo = friendIdMap.get(record.getFriendId());
                UsersVo usersVo = BeanUtil.toBeanIgnoreError(userInfo, UsersVo.class);
                usersVo.setUserId("HX_" + userInfo.getUserId());
                usersVo.setGender(userInfo.getSex().name().toLowerCase());
                usersVo.setCity(StrUtil.subBefore(userInfo.getCity(), '-', false));
                result.add(usersVo);
            }
        } else {
            // 把所有的联系人查询出来，再进行筛选
            List<Users> usersList = this.usersApi.queryAllUsersList(userId);
            if (CollUtil.isEmpty(usersList)) {
                return pageResult;
            }
            List<Object> friendIdList = CollUtil.getFieldValues(usersList, "friendId");
            userInfoList = this.userInfoApi.queryListLikeNickName(friendIdList, keyword);
            //封装UsersVo
            for (UserInfo userInfo : userInfoList) {
                UsersVo usersVo = BeanUtil.toBeanIgnoreError(userInfo, UsersVo.class);
                usersVo.setUserId("HX_" + userInfo.getUserId());
                usersVo.setGender(userInfo.getSex().name().toLowerCase());
                usersVo.setCity(StrUtil.subBefore(userInfo.getCity(), '-', false));
                result.add(usersVo);
            }
        }

        pageResult.setItems(result);
        return pageResult;
        }




    /**
     * 删除好友
     *
     * @param userId 好友id
     */
    public void removeUser(Long userId) {
        //删除好友关系
        Long myId = UserThreadLocal.get();
        Boolean result = this.usersApi.removeUsers(myId, userId);
        if(result){
            //将环信平台的好友关系解除
            this.huanXinApi.removeUserFriend(myId, userId);
        }
    }


    //查询点赞列表
    public PageResult qureyLikeCommentList(Integer page, Integer pageSize) {
        Long userId = UserThreadLocal.get();
        PageInfo<Comment> pageInfo = this.quanZiApi.qureyLikeCommentListByUser(userId, page, pageSize);
        return addDataToPageResult(pageInfo);
    }

    //查询喜欢列表
    public PageResult qureyLoveCommentList(Integer page, Integer pageSize) {
        Long userId = UserThreadLocal.get();
        PageInfo<Comment> pageInfo = this.quanZiApi.qureyLoveCommentList(userId, page, pageSize);
        return addDataToPageResult(pageInfo);

    }

    //查询评论信息列表
    public PageResult qureyCommentsCommentList(Integer page, Integer pageSize) {
        Long userId = UserThreadLocal.get();
        PageInfo<Comment> pageInfo = this.quanZiApi.qureyCommentsCommentList(userId, page, pageSize);
        return addDataToPageResult(pageInfo);
    }

    //查询消息公告列表

    public PageResult qureyAnnouncementsCommentList(Integer page, Integer pageSize) {
        IPage<Announcement> announcementIPage = this.announcementService.qureyAnnouncementsCommentList(page, pageSize);
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        List<Announcement> records = announcementIPage.getRecords();
        if (CollUtil.isEmpty(records)){
            return pageResult;
        }
        List<AnnouncementVo> announcementVoList = new ArrayList<>();

        for (Announcement record : records) {
            AnnouncementVo announcementVo = new AnnouncementVo();
            announcementVo.setId(record.getId().toString());
            announcementVo.setTitle(record.getTitle());
            announcementVo.setDescription(record.getDescription());
            announcementVo.setCreateDate(DateUtil.format(record.getCreated(), "yyyy-MM-dd HH:mm"));

            announcementVoList.add(announcementVo);
        }
        pageResult.setItems(announcementVoList);

        return pageResult;
    }


    private PageResult addDataToPageResult(PageInfo<Comment> pageInfo) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(pageInfo.getPageNum());
        pageResult.setPagesize(pageInfo.getPageSize());
        List<Comment> records = pageInfo.getRecords();
        //判断是否为空
        if (CollUtil.isEmpty(records)) {
            //为空直接返回
            return pageResult;
        }

        List<Object> userIdList = CollUtil.getFieldValues(records, "userId");
        Map<Long, UserInfo> userInfoMap = this.userInfoApi.queryMapByUserIdList(userIdList);
        List<MessageCommentVo> messageCommentVoList = new ArrayList<>();
        for (Comment record : records) {
            UserInfo userInfo = userInfoMap.get(record.getUserId());
            if (ObjectUtil.equal(record.getUserId(), userInfo.getUserId())) {
                MessageCommentVo messageCommentVo = BeanUtil.toBeanIgnoreError(userInfo, MessageCommentVo.class);
                messageCommentVo.setCreateDate(DateUtil.now());
                messageCommentVoList.add(messageCommentVo);
            }
        }
        pageResult.setItems(messageCommentVoList);
        return pageResult;

    }
}

